package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.PermissionUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.widget.AndroidScheduler;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;

public class IconActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    private String ori_img = "https://pandapo.oss-cn-hangzhou.aliyuncs.com/571bc39c-62b5-4141-91a3-e5095b3877b2.png";
    private ImageView icon_iv;

    private String[] perms = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private int DEDIA_PERMS = 1001;

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            ToastUtil.show("请您前往本手机设置手动开启权限");
        }
    }

    private class BottomIconDialog extends BottomSheetDialog {
        public BottomIconDialog(@NonNull Context context) {
            super(context);
        }

        public BottomIconDialog(@NonNull Context context, int themeResId) {
            super(context, themeResId);
        }

        protected BottomIconDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        public void showBottomDialog(Context context) {
            Dialog dialog = new BottomSheetDialog(context, R.style.DialogTheme);
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_bottom_icon, null);
            dialog.setContentView(view);
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();

            dialog.findViewById(R.id.dialog_bot_icon_tv_album).setOnClickListener(v -> {
                if (!EasyPermissions.hasPermissions(IconActivity.this, perms)) {
                    EasyPermissions.requestPermissions(IconActivity.this, "请授予APP摄像头和存储读写权限", DEDIA_PERMS, perms);
                }else {
                    dialog.dismiss();
                    openAlbum();
                }
            });

            dialog.findViewById(R.id.dialog_bot_icon_tv_camera).setOnClickListener(v -> {
                if (!EasyPermissions.hasPermissions(IconActivity.this, perms)) {
                    EasyPermissions.requestPermissions(IconActivity.this, "请授予APP摄像头和存储读写权限", DEDIA_PERMS, perms);
                }else {
                    dialog.dismiss();
                    if (PermissionUtil.checkPermission(IconActivity.this,
                            Manifest.permission.CAMERA,
                            R.id.dialog_bot_icon_tv_camera % 4096)) {
                        try {
                            dispatchTakePictureIntent();
                        } catch (CameraAccessException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });

            dialog.findViewById(R.id.dialog_bot_icon_tv_recover).setOnClickListener(v -> {
                dialog.dismiss();
                changeIcon(ori_img);
            });

            dialog.findViewById(R.id.dialog_bot_icon_tv_cancel).setOnClickListener(v -> dialog.dismiss());
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_icon;
    }

    @Override
    protected boolean initView() {
        icon_iv = findViewById(R.id.icon_iv);
        icon_iv.setLongClickable(true);
        icon_iv.setOnLongClickListener(view -> {
            new BottomIconDialog(IconActivity.this).showBottomDialog(IconActivity.this);
            return true;
        });
        return true;
    }

    @Override
    protected boolean initData() {
        Glide.with(IconActivity.this)
                .load(UserManager.getInstance().getImage())
                .into(icon_iv);
        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void setIconRecovery(String img) {
        Glide.with(this)
                .load(img)
                .into(icon_iv);
    }


    private void dispatchTakePictureIntent() throws CameraAccessException {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            String[] cameraIds = cameraManager.getCameraIdList();
            if (cameraIds.length > 0) {
                if (cameraIds[0] != null || cameraIds[1] != null) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePictureIntent, R.id.dialog_bot_icon_tv_camera % 4096);
                }
            }
        } else {
            ToastUtil.show("摄像头不可用");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == R.id.dialog_bot_icon_tv_camera % 4096 && resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = (Bitmap) extras.get("data");
                    if (photo != null) {
                        File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                                "Camera");
                        if (!dir.exists())
                            dir.mkdirs();

                        String fileName = "IMG_" + System.currentTimeMillis() + ".jpg";
                        File photoFile = new File(dir, fileName);

                        try {
                            FileOutputStream fos = new FileOutputStream(photoFile);
                            photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                            fos.flush();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // 上传图片文件
                        if (photoFile != null) {
                            String imagePath = photoFile.getAbsolutePath();
                            cropImage(Uri.fromFile(new File(imagePath)));
                        }
                    }
                }
            } else if (requestCode == R.id.dialog_bot_icon_tv_album % 4096 && resultCode == RESULT_OK) {
                cropImage(data.getData());
            } else if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
                Uri resultUri = UCrop.getOutput(data);
                if (resultUri != null)
                    uploadImage(new File(resultUri.getPath()));
            } else if (resultCode == UCrop.RESULT_ERROR) {
                final Throwable cropError = UCrop.getError(data);
                cropError.printStackTrace();
            }

        }
    }


    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, R.id.dialog_bot_icon_tv_album % 4096);
    }


    private void changeIcon(String img) {
        String img_0 = UserManager.getInstance().getImage();
        UserManager.getInstance().setImage(img);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
                UserManager.getInstance().getInfo());
        RetrofitHelper.getInstance().create()
                .change_info(requestBody, String.valueOf(UserManager.getInstance().getUserId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        if (value.getCode() == SUCCESS) {
                            ToastUtil.show("修改成功");
                            LogUtil.d(value.getMessage() + "\n" + value.getData());
                            setIconRecovery(img);
                        } else {
                            showErrorDialog("修改失败，请重试" + value.getMessage());
                            LogUtil.e(value.getMessage() + "\n" + value.getData());
                            UserManager.getInstance().setImage(img_0);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showErrorDialog("修改失败，请重试" + e.getMessage());
                        UserManager.getInstance().setImage(img_0);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void uploadImage(File file) {
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part
                .createFormData("file", file.getName(), imageBody);
        RetrofitHelper.getInstance().create().upload(String.valueOf(UserManager.getInstance().getUserId()), part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        if (value.getCode() == SUCCESS) {
                            changeIcon(String.valueOf(value.getData()));
                            LogUtil.d(value.getMessage() + "\n" + value.getData());
                        } else {
                            showErrorDialog("上传服务器失败，请重试");
                            LogUtil.e("uploadImage fail" + value.getCode() + "\n" + value.getMessage() + "\n" + value.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showErrorDialog("上传服务器失败，请重试");
                        LogUtil.e("uploadImage error" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void cropImage(Uri sourceUri) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageFileName + ".jpg"));

        UCrop uCrop = UCrop.of(sourceUri, destinationUri);
        UCrop.Options options = new UCrop.Options();
        options.setHideBottomControls(true);

        uCrop.withOptions(options);
        uCrop.withAspectRatio(1, 1);
        uCrop.start(this);
    }
}